package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.modular.system.entity.CashOut;
import cn.stylefeng.guns.modular.system.enums.ResultEnum;
import cn.stylefeng.guns.modular.system.exception.ProjectException;
import cn.stylefeng.guns.modular.system.service.AppCashOutService;
import cn.stylefeng.guns.modular.system.service.ProxyIncomeService;
import cn.stylefeng.guns.modular.system.service.ProxyUserService;
import cn.stylefeng.guns.modular.system.utils.ResultVOUtil;
import cn.stylefeng.guns.modular.system.vo.ResultVO;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.util.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ProxyIncomeController
 * @Author lzy
 * @Date 2020/2/9 16:27
 * @VERSION 1.0
 **/
@Controller
@RequestMapping("/proxyIncome")
public class ProxyIncomeController {

    private final static Logger log = LoggerFactory.getLogger(ProxyIncomeController.class);

    private static final String SECCESS = "SECCESS";

    private String PREFIX = "/modular/system/proxyIncome/";

    @Autowired
    private ProxyIncomeService proxyIncomeService;

    @Autowired
    private AppCashOutService appCashOutService;

    @Autowired
    private ProxyUserService proxyUserService;
    /**
     * 跳转到主页面
     *
     * @author lzy
     * @Date 2019-06-20
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "proxyIncome.html";
    }

    /**
     * 跳转添加页面
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/withdrawal")
    public String add() {
        return PREFIX + "proxyIncome_withdrawal.html";
    }


    @GetMapping("/findProxyIncomeById")
    @ResponseBody
    public ResultVO proxyIncome(@RequestParam(value = "startTime", required = false) String startTime,
                                @RequestParam(value = "endTime", required = false)String endTime,
                                @RequestParam(value = "proxyName", required = false)String proxyName,
                                @RequestParam("page")Integer pageNum, @RequestParam("limit") Integer pageSize){

        Long id = LoginContextHolder.getContext().getUserId();
        log.info("代理人id"+id);
        Assert.isTrue(!ObjectUtils.isEmpty(id), ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());
        //每个代理只能查出自己的存取款记录和旗下代理的存取款记录
        List<String> userIds = proxyIncomeService.findIdsByProxyId(id);
        //加上自己的id
        userIds.add(id.toString());
        if(userIds.size() == 0){
            return ResultVOUtil.success(SECCESS);
        }
        //设置默认分页参数
        PageHelper.startPage(pageNum,pageSize);
        List<Map<Object,Object>> syss = proxyIncomeService.findList(startTime,endTime,proxyName,userIds);
        PageInfo<Map<Object,Object>> pageInfo = new PageInfo<>(syss);

        return ResultVOUtil.success(pageInfo.getList(),pageInfo.getTotal());
    }


    /**
     * 提现
     * @param money 提现金额
     * @param password 密码
     * @return
     */
    @RequestMapping("/proxyWithdrawal")
    @ResponseBody
    public ResultVO proxyWithdrawal(@RequestParam("money") BigDecimal money,
                               @RequestParam("password") String password){
        //代理提现 获取当前代理信息，传入提现金额与密码并且判断是否合适，合适则生成一个订单，不合适报错
        Long id = LoginContextHolder.getContext().getUserId();
        User user = proxyUserService.selectProxy(id);

        Assert.isTrue(!ObjectUtils.isEmpty(money),ResultEnum.CODE_NOT_EXIST.getMessage());
        Assert.isTrue(!ObjectUtils.isEmpty(password),ResultEnum.CODE_NOT_EXIST.getMessage());
        //判断密码是否匹配
        String userPwd = user.getPassword();
        password = MD5Util.encrypt(MD5Util.encrypt(password
                + user.getEmail() + user.getPhone() + user.getSalt()));
        if(!userPwd.equals(password)){
            return ResultVOUtil.error(new ProjectException("密码错误"));
        }
        //如果去除提现金额，余额不足以支付6/1000的提取费则报错余额不足
        //余额只要小于withdrawalAmount就报错余额不足
        BigDecimal withdrawalAmount = money.multiply(new BigDecimal(6 / 1000)).add(money);
        if(user.getMoney().compareTo(withdrawalAmount) == -1){
            return ResultVOUtil.error(new ProjectException("余额不足"));
        }
        //生成订单的同时，代理后台的money减去withdrawalAmount然后更新代理数据
        user.setMoney(user.getMoney().subtract(withdrawalAmount));
        CashOut cashOut = new CashOut();
        //TODO  需要做完代理银行卡的添加之后才能继续下去，流程为，根据代理用户查出他的银行卡id。然后插入字段，已经写好，需要先写完银行卡相关数据
//TODO        cashOut.setCard(user.getCardId());
        cashOut.setDateTime(new Date());
        cashOut.setMoney(money);
        cashOut.setStatus(1);
        cashOut.setUserId(id.intValue());
        appCashOutService.withdrawal(user,cashOut);
        return ResultVOUtil.success("SUCCESS");
    }

}
